/* 
 * Copyright 2012 DevDan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.devdan.headsetfix;



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import static com.devdan.headsetfix.HeadsetCommonConstants.*;

public class ButtonPressedReceiver extends BroadcastReceiver {
	
	private boolean ignoreNext;
    private static ButtonPressedReceiver instance;
    private int buttonBehaviour;
    private String phoneNumber;
	public static final int LONG_PRESS_THRESHOLD = 800;
	public static final long INVALID_TIME_STAMP = -1;
	private static final String TAG = null;
	
	private static long buttonDownTime = INVALID_TIME_STAMP;
	
    @Override
	public void onReceive(Context context, Intent intent) {
    	if (!ignoreNext) {
		    if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
		    	KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
		    	int action = event.getAction();
		    	// Save time when button was pressed down to check for normal or long press later
		    	if (action == KeyEvent.ACTION_DOWN) {
		    		// When button is pressed longer, multiple ACTION_DOWN events could occur. Make sure that
		    		// the original button down time is not overwritten.
		    		if  (buttonDownTime == INVALID_TIME_STAMP) {
		    			buttonDownTime = event.getEventTime();
		    		}
		    	}
		    	// Dial when the button was released again
		    	if (action == KeyEvent.ACTION_UP) {
		    		// and only if the button was long pressed
		    		if (event.getEventTime() - buttonDownTime > LONG_PRESS_THRESHOLD) {			    	
			            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			            if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
			    	    	// Abort broadcast, otherwise media player will start (or stop) playing.
			                if (isOrderedBroadcast()) {
			                    abortBroadcast();
			                }				                
			    			switch (buttonBehaviour)
			    			{
			    				case OPTION_REDIAL:
			    					redial(context);
			    					break;
			    				case OPTION_VOICE_DIALER:
			    					showVoiceDialer(context);
			    					break;
			    				case OPTION_DIAL_NUMBER:
			    					dialNumber(context);
			    					break;
			    			}
			            }	
		    		}
		    		buttonDownTime = INVALID_TIME_STAMP;
		    	}
		    }	
    	}
    	else {
    		ignoreNext = false;
    	}
    	Log.d(TAG,String.valueOf(buttonDownTime));
    	
	}



	public static ButtonPressedReceiver getInstance()
    {
        if(instance == null)
        {
            instance = new ButtonPressedReceiver();            
        }
        return instance;
    }
    
    public void setButtonBehaviour(int behaviour) {
    	buttonBehaviour = behaviour;
    }
    
	private void redial(Context context) {
		String number = android.provider.CallLog.Calls.getLastOutgoingCall(context);
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +  number));
        callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(callIntent);
	}
	
	private void showVoiceDialer(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClassName("com.android.voicedialer", "com.android.voicedialer.VoiceDialerActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        
        context.startActivity(intent);
		
	}

    private void dialNumber(Context context) {
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +  phoneNumber));
        callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(callIntent);    	
	}
    
    
	public void setIgnoreNext() {
		ignoreNext = true;
	}
	public void setPhoneNumber(String number) {
		phoneNumber = number;
	}
}